package com.health.system.process.receiver;

import com.health.system.model.DataStatsTask;
import com.health.system.model.constant.DataStatsTaskQueueConstants;
import com.health.system.model.constant.DelayDeleteQueueConstants;
import com.health.system.process.util.DBUtil;
import com.health.system.process.util.DataToExcel;
import com.health.system.process.util.QiNiuUtil;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Component
public class DataStatsTaskReceiver {
    public static final Logger logger = LoggerFactory.getLogger(DataStatsTaskReceiver.class);

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    DBUtil dbUtil;

    static String path = System.getProperty("java.io.tmpdir")+ File.separator;

    @RabbitListener(queues = DataStatsTaskQueueConstants.STATS_TASK_QUEUE_NAME)
    public void handler(Message message, Channel channel) throws IOException {
        DataStatsTask dataStatsTask = (DataStatsTask) message.getPayload();
        MessageHeaders headers = message.getHeaders();
        Long tag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        String msgId = (String) headers.get("spring_returned_message_correlation");
        logger.info("Received Task:{}",dataStatsTask.toString());
        if (redisTemplate.opsForHash().entries("stats_task_log").containsKey(msgId)) {
            //redis 中包含该 key，说明该消息已经被消费过
            logger.info(msgId + ":消息已经被消费");
            channel.basicAck(tag, false);//确认消息已消费
            return;
        }
        String sql = dataStatsTask.getSql();
        String key = dataStatsTask.getTaskId();
        redisTemplate.opsForHash().put("export_task",dataStatsTask.getTaskId(),"processing");
        if(dbUtil.extractToExcel(sql,path,key)){
            String local = path+key;
            String url = QiNiuUtil.upload(local,key);
            if(url==null){
                redisTemplate.opsForHash().delete("export_task",dataStatsTask.getTaskId());
                return;
            }
            redisTemplate.opsForHash().put("export_task",dataStatsTask.getTaskId(),url);
            sendDelayTask(key,dataStatsTask.getExpired());
        }
    }

    public void sendDelayTask(String msg,Integer delayTime){
        rabbitTemplate.convertAndSend(DelayDeleteQueueConstants.DELAY_DELETE_EXCHANGE_NAME,
                DelayDeleteQueueConstants.DELAY_DELETE_ROUTING_KEY_NAME, msg, a ->{
            a.getMessageProperties().setDelay(delayTime);
            return a;
        });
    }
}
